var userDAO = require('../models/userDAO')
var formidable = require('formidable')
var path = require('path')
var bcrypt = require('bcrypt')
var userController = {
    // getAllUsers: function (req, res) {
    //     userDAO.getAllUsers(function (err, results) {
    //         if (err) {
    //             res.json({ code: 500, msg: '用户信息查询失败！' })
    //         } else {
    //             res.json({ code: 200, data: results, msg: '用户查询成功!' })
    //         }
    //     })
    // },
    register:function(req,res){
        var user = {userTel:req.body.telephone,userPwd:req.body.userPassword}
        bcrypt.genSalt(10,function(err,salt){
            bcrypt.hash(user.userPwd,salt,function(err,hash){
                user.userPwd = hash
                userDAO.register(user,function(err,results){
                    if(err){
                        res.status(500).json({msg:'数据库错误，注册失败!'})
                    }else{
                        res.status(200).json({msg:'注册成功!'})
                    }
                })
            });
        });
    },
    login:function(req,res){
        var user = {userTel:req.body.telephone,userPwd:req.body.userPassword}
        userDAO.getUserByTel(user.userTel,function(err,results){
            if(err){
                res.status(500).json({msg:'数据库错误，登录失败'})
            }else{
                if(results == null || results.length !=1){
                    res.status(200).json({msg:'手机号不存在，登录失败!'})
                }else{
                    bcrypt.compare(user.userPwd,results[0].userPwd,function(err,resPwd){
                           if(resPwd){
                            jwt.sign({userTel: user.userTel},'privateKey',{expiresIn:60*60},function(err,token){
                                console.log(token);
                                res.status(200).json({msg:'登录成功！！',token: 'Bearer' +token})
                      });
                           }else{
                               res.status(200).json({msg:'密码错误，登录失败！！'})
                           }
                    })
                }
            }
        })
    }
}
    module.exports = userController